<template>
  <div class="body">
    <el-row>
      <el-col :span="3">
        <el-input
          v-model="ser.employee_name"
          placeholder="请输入员工名称"
        ></el-input>
      </el-col>
      <el-col :span="4">
        <el-input
          v-model="ser.card_number"
          disabled
          placeholder="请读取卡片信息"
          style="margin-left: 10px"
        >
          <el-button
            @click="getkas"
            slot="append"
            icon="el-icon-plus"
            style="background: #1890ff; color: #fff"
            >读卡</el-button
          >
        </el-input>
      </el-col>
      <el-col :span="12">
        <el-button class="add_btn" @click="dwone_duka"
          >读卡通讯程序下载</el-button
        >
        <el-button
          @click="company_name_click(0)"
          icon="el-icon-search"
          class="add_btn"
        >
          搜索</el-button
        >
        <el-button
          icon="el-icon-refresh"
          @click="company_name_clicks"
          class="add_btn"
        >
          重置</el-button
        >
        <el-button @click="add_product" icon="el-icon-plus" class="add_btn"
          >新增员工</el-button
        >
      </el-col>
    </el-row>

    <el-table
      :data="productList"
      v-loading="loading"
      stripe
      style="width: 100%"
      border
    >
      <el-table-column prop="id" label="ID" width="180"> </el-table-column>
      <el-table-column prop="employee_name" label="员工名称" width="180">
      </el-table-column>
      <el-table-column prop="level" label="员工等级" width="180">
      </el-table-column>
      <el-table-column prop="username" label="账号">
        <template slot-scope="scope">
          <span>{{ scope.row.user ? scope.row.user.username : "" }}</span>
        </template>
      </el-table-column>
      <el-table-column prop="password" label="密码">
        <template slot-scope="scope">
          <span>{{ scope.row.user ? scope.row.user.password : "" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工种" width="120">
        <template slot-scope="scope">
          <span
            v-for="item in scope.row.user.job_type"
            style="display: block"
            >{{ item.job_type }}</span
          >
        </template>
        <!-- <template slot-scope="scope">
          {{
            scope.row.job_type
            ? scope.row.job_type.job_type
            : scope.row.user.role[0].name
              ? scope.row.user.role[0].name
              : ""
          }}
        </template> -->
      </el-table-column>
      <el-table-column label="是否是工长" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.is_foreman == 1 ? "是" : "否" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工长关联工种" width="120">
        <template slot-scope="scope">
          <span
            v-for="(item, index) in scope.row.foreman_job_type"
            style="display: block"
            :key="index"
            >{{ item.job_type }}</span
          >
        </template>
      </el-table-column>
      <el-table-column prop="phone" label="电话" width="150">
        <template slot-scope="scope">
          <span>{{ scope.row.user ? scope.row.user.phone : "" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="详细地址" prop="address" width="200">
      </el-table-column>
      <el-table-column label="籍贯" width="200">
        <template slot-scope="scope">
          <span>{{ scope.row.native_place }}</span>
        </template>
      </el-table-column>
      <el-table-column label="紧急联系人" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.emergency_contact }}</span>
        </template>
      </el-table-column>
      <el-table-column label="紧急联系电话" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.emergency_contact_phone }}</span>
        </template>
      </el-table-column>
      <el-table-column label="工号" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.card_number }}</span>
        </template>
      </el-table-column>
      <el-table-column label="基本工资" width="120">
        <template slot-scope="scope">
          <span>{{ scope.row.base_pay }}</span>
        </template>
      </el-table-column>
      <el-table-column label="入职时间" width="120" :formatter="formatterTime">
        <template slot-scope="scope">
          <span>{{
            scope.row.hiredate ? scope.row.hiredate.slice(0, 11) : ""
          }}</span>
        </template>
      </el-table-column>
      <el-table-column label="提交方式" width="100">
        <template slot-scope="scope">
          <span>{{ scope.row.submit_way == 1 ? "手动" : "自动" }}</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" fixed="right" width="150">
        <template slot-scope="scope">
          <el-button
            @click="set_product(scope.row)"
            type="text"
            icon="el-icon-edit"
            >编辑</el-button
          >
          <el-popconfirm
            confirm-button-text="确定"
            cancel-button-text="取消"
            icon="el-icon-info"
            icon-color="red"
            title="是否删除这条数据？"
            @confirm="del_product(scope.row)"
          >
            <el-button slot="reference" type="text" icon="el-icon-delete">
              删除</el-button
            >
          </el-popconfirm>
        </template>
      </el-table-column>
    </el-table>
    <div class="pagination">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        background
        @prev-click="prev"
        @next-click="next"
        :current-page.sync="pagination.page"
        :page-size="pagination.per_page"
        layout="total, prev, pager, next"
        :total="total"
      >
      </el-pagination>
    </div>

    <el-dialog
      :title="title"
      :visible.sync="isProduct"
      width="50%"
      :close-on-click-modal="false"
      @close="dialog_click"
    >
      <el-form
        :model="ruleForm"
        :rules="rules"
        ref="ruleForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-row>
          <el-col :span="12">
            <el-form-item label="选择员工" prop="users_id">
              <el-select
                v-model="ruleForm.users_id"
                placeholder="请选择员工"
                style="width: 100%"
                @change="changeValue"
              >
                <el-option
                  v-for="item in YuanGongList"
                  :key="item.id"
                  :label="item.username"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="入职时间" prop="hiredate">
              <el-date-picker
                style="width: 100%"
                v-model="ruleForm.hiredate"
                type="date"
                format="yyyy 年 MM 月 dd 日"
                value-format="yyyy-MM-dd"
                placeholder="选择日期"
              >
              </el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="工种" prop="job_type_id">
              <el-select
                v-model="ruleForm.job_type_arr"
                clearable
                multiple
                placeholder="请选择"
                style="width: 100%"
                @change="changeValue"
              >
                <el-option
                  v-for="item in dataList"
                  :key="item.id"
                  :label="item.job_type"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="联系电话">
              <el-input
                v-model="ruleForm.phones"
                @input="changeValue"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="基本工资" prop="base_pay">
              <el-input
                v-model="ruleForm.base_pay"
                @input="changeValue"
              ></el-input>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="身份证号" prop="id_card">
              <el-input
                v-model="ruleForm.id_card"
                @input="changeValue"
              ></el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="详细地址" prop="address">
              <el-input
                v-model="ruleForm.address"
                @input="changeValue"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="籍贯" prop="native_place">
              <el-input
                v-model="ruleForm.native_place"
                @input="changeValue"
              ></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="紧急联系人" prop="emergency_contact">
              <el-input
                v-model="ruleForm.emergency_contact"
                @input="changeValue"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="12">
            <el-form-item label="是否工长">
              <el-radio-group v-model="ruleForm.is_foreman">
                <el-radio :label="1">是</el-radio>
                <el-radio :label="0">否</el-radio>
              </el-radio-group>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="卡号" prop="card_number">
              <el-input v-model="ruleForm.card_number" @input="changeValue" disabled>
                <el-button @click="getka" slot="append" icon="el-icon-plus"
                  style="background: #1890ff; color: #fff">读卡</el-button>
              </el-input>
            </el-form-item>
          </el-col> -->
          <el-col :span="12">
            <el-form-item label="紧急联系电话" prop="emergency_contact_phone">
              <el-input
                v-model="ruleForm.emergency_contact_phone"
                @input="changeValue"
              ></el-input>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-if="is_job">
          <el-col :span="12">
            <el-form-item label="工长关联工种" prop="job_type_id">
              <el-select
                v-model="ruleForm.foreman_job_type_ids"
                clearable
                multiple
                placeholder="请选择"
                style="width: 100%"
                @change="changeValue"
              >
                <el-option
                  v-for="item in dataList"
                  :key="item.id"
                  :label="item.job_type"
                  :value="item.id"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>
          <!-- <el-col :span="12">
            <el-form-item label="基本工资" prop="base_pay">
              <el-input
                v-model="ruleForm.base_pay"
                @input="changeValue"
              ></el-input>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="读卡通讯程序下载" label-width="130px">
              <el-button @click="dwone_duka" style="float: left">下载</el-button>
            </el-form-item>
          </el-col> -->
          <!-- <el-col :span="12">
            <el-form-item label="等级" prop="level">
              <el-select style="width: 100%" v-model="ruleForm.level" placeholder="请选择等级">
                <el-option v-for="item in live" :key="item" :label="item" :value="item">
                </el-option>
              </el-select>
            </el-form-item>
          </el-col> -->
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="isProduct = false" style="margin-right: 15px"
          >取 消</el-button
        >
        <el-button type="primary" @click="submitadd('ruleForm')"
          >确定</el-button
        >
      </span>
    </el-dialog>

    <el-dialog title="提示" :visible.sync="dialogVisible_box" width="30%">
      <span
        >当前卡片已绑定给<span
          v-for="(item, index) in name_list"
          :key="index"
          style="margin-right: 5px"
          >【{{ item.name }}】</span
        ></span
      >
      <p>
        确定要继续使用当前卡片吗？确定后将清除
        <span
          v-for="(item, index) in name_list"
          :key="index"
          style="margin-right: 5px"
          >【{{ item.name }}】</span
        >的绑定信息！
      </p>

      <span slot="footer" class="dialog-footer">
        <el-button @click="clear_EmployeeCardId_false">取 消</el-button>
        <el-button type="primary" @click="clear_EmployeeCardId"
          >确 定</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
import {
  getEmployeeList,
  createEmployee,
  delEmployee,
  getJobTypeList,
  clearEmployeeCardId,
  getYuanGongList,
} from "@/api/product/index";
import { getRoleList } from "@/api/role/index";

import {
  regionDataPlus,
  CodeToText,
  TextToCode,
} from "element-china-area-data";
export default {
  data() {
    var checkphone = (rule, value, callback) => {
      // let phoneReg = /(^\d{10,11}$)/;
      if (value === "") {
        callback(new Error("请输入手机号"));
      } else if (value.length > 11) {
        callback(new Error("请输入正确的手机号!"));
      } else {
        callback();
      }
    };
    return {
      name_list: [],
      dialogVisible_box: false,
      live: [1, 2, 3, 4, 5, 6, 7],
      loading: true,
      formatterTime(row, column) {
        let data = row[column.property];
        return /\d{4}-\d{1,2}-\d{1,2}/g.exec(data);
      },
      ser: {
        employee_name: "",
        card_number: "",
      },
      isset: false,
      roleList: [],
      title: "",
      isProduct: false,
      productList: [],
      ruleForm: {
        users_id: "",
        level: 1,
        job_type_arr: [],
        foreman_job_type_ids: [],
        phones: "",
        address: "",
        native_place: "", //籍贯
        emergency_contact: "", //紧急联系人
        emergency_contact_phone: "", //紧急联系电话
        card_number: "", //工号
        base_pay: "", //基本工资
        hiredate: "", //入职时间
        submit_way: "1", //提交方式
        id_card: "",
        is_foreman: 0,
        id: "",
      },
      rules: {
        users_id: [
          {
            required: true,
            message: "请选择员工",
            trigger: "blur",
          },
        ],
        // usernames: [
        //   {
        //     required: true,
        //     message: "请输入员工APP账号",
        //     trigger: "blur",
        //   },
        // ],
        // passwords: [
        //   {
        //     required: true,
        //     message: "请输入员工APP密码",
        //     trigger: "blur",
        //   },
        // ],
        // employee_name: [
        //   {
        //     required: true,
        //     message: "请输入员工名称",
        //     trigger: "blur",
        //   },
        // ],
        phones: [
          {
            required: true,
            validator: checkphone,
            trigger: "blur",
          },
        ],
      },
      options: regionDataPlus,
      selectedOptions: [],
      pagination: {
        per_page: 10,
        page: 1,
      },
      total: 0,
      dataList: [],
      YuanGongList: [],
      is_job: false,
    };
  },
  mounted() {
    this.getlist();
  },
  watch: {
    "ruleForm.is_foreman"(news, olds) {
      if (news == 1) {
        this.is_job = true;
      } else {
        this.is_job = false;
      }
    },
    // "ruleForm.card_number"(a, b) {
    //   if (a) {
    //     this.company_name_click_box(a);
    //   }
    // },
  },
  methods: {
    get_YuanGongList() {
      getYuanGongList().then((res) => {
        if (res.code == 200) {
          this.YuanGongList = res.data;
        }
      });
    },
    clear_EmployeeCardId_false() {
      this.ruleForm.card_number = "";
      this.dialogVisible_box = false;
    },
    clear_EmployeeCardId() {
      console.log(this.name_list);
      let users_id = [];
      this.name_list.forEach((item) => {
        users_id.push(item.id);
      });
      clearEmployeeCardId({ users_ids: users_id }).then((res) => {
        if (res.code == 200) {
          this.$message.success("清除成功");
          this.dialogVisible_box = false;
        }
      });
    },
    dwone_duka() {
      window.open("https://api.likai.vip/exe/card.exe", "_blank");
    },
    getkas() {
      var that = this;
      that
        .$axios("http://127.0.0.1:9191/getCardId")
        .then(function (response) {
          console.log(response.data);
          if (response.data.state == 0) {
            that.ser.card_number = response.data.cardid;
            that.getlist();
          }
        })
        .catch(function (err) {
          that.$message.error("请下载并启动读卡通讯程序或检查读卡器是否接入~");
          console.log(err);
        });
    },
    getka() {
      var that = this;
      that
        .$axios("http://127.0.0.1:9191/getCardId")
        .then(function (response) {
          console.log(response.data);
          if (response.data.state == 0) {
            that.ruleForm.card_number = response.data.cardid;
            this.company_name_click_box(response.data.cardid);
          }
        })
        .catch(function (err) {
          console.log(err);
          that.$message.error("请下载并启动读卡通讯程序或检查读卡器是否接入~");
        });
    },
    dialog_click() {
      this.ruleForm = {
        users_id: "",
        level: 1,
        is_foreman: 0,
        job_type_arr: [],
        foreman_job_type_ids: [],
        phones: "",
        address: "",
        native_place: "", //籍贯
        emergency_contact: "", //紧急联系人
        emergency_contact_phone: "", //紧急联系电话
        card_number: "", //工号
        base_pay: "", //基本工资
        hiredate: "", //入职时间
        submit_way: "1", //提交方式
        id_card: "",
        id: "",
      };
      this.$nextTick();
      this.isset = false;
    },
    getrole() {
      getRoleList().then((res) => {
        if (res.code == 200) {
          this.roleList = res.data.data;
        }
      });
    },
    getType() {
      getJobTypeList({ is_simple: 1, per_page: 9999 }).then((res) => {
        if (res.code == 200) {
          this.dataList = res.data.data;
        }
      });
    },
    del_product(row) {
      console.log("ww");
      delEmployee({
        id: row.id,
        is_del: 1,
      }).then((res) => {
        if (res.code == 200) {
          this.isProduct = false;
          this.$message.success("提交成功");
          this.getlist();
        }
      });
    },
    handleChange(value) {
      console.log("21121212", value);
      let position = `${CodeToText[value[0]]}/${CodeToText[value[1]]}/${
        CodeToText[value[2]]
      }`;
      let arry = position.split("/");
      this.ruleForm.province = arry[0];
      this.ruleForm.city = arry[1];
      this.ruleForm.county = arry[2];
    },
    getlist() {
      getEmployeeList({ ...this.pagination, ...this.ser }).then((res) => {
        if (res.code == 200) {
          this.productList = res.data.data;
          this.total = res.data.total;
          this.loading = false;
        }
      });
    },
    company_name_click(type) {
      if (type == 0) {
        this.pagination.per_page = 10;
        this.pagination.page = 1;
      }
      getEmployeeList({ ...this.ser, ...this.pagination }).then((res) => {
        if (res.code == 200) {
          this.productList = res.data.data;
          this.total = res.data.total;
        }
      });
    },
    company_name_click_box(num) {
      getEmployeeList({ card_number: num }).then((res) => {
        if (res.code == 200) {
          if (res.data.data.length > 0) {
            let name = [];
            res.data.data.forEach((item) => {
              let obj = {
                name: item.employee_name,
                id: item.user_id,
              };
              name.push(obj);
            });
            this.dialogVisible_box = true;
            this.name_list = name;
            // this.$message.success("警告！此卡已绑定员工" + name);
            // this.ruleForm.card_number;
          }
        }
      });
    },
    company_name_clicks() {
      this.ser.company_name = "";
      getEmployeeList(this.pagination).then((res) => {
        if (res.code == 200) {
          this.productList = res.data.data;
          this.total = res.data.total;
        }
      });
    },

    add_product() {
      this.title = "新增员工";
      this.isProduct = true;
      this.isset = false;
      this.getType();
      this.getrole();
      this.get_YuanGongList();
    },
    submitadd(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          createEmployee(this.ruleForm).then((res) => {
            if (res.code == 200) {
              this.isProduct = false;
              this.$message.success("提交成功");
              this.getlist();
              this.$nextTick(function () {
                this.$refs.ruleForm.resetFields();
              });
            }
          });
        } else {
          console.log("error submit!!");
          return false;
        }
      });
    },
    set_product(row) {
      this.getType();
      this.getrole();
      this.get_YuanGongList();
      console.log(row);
      // this.ruleForm.employee_name = row.employee_name;
      this.ruleForm.users_id = row.user_id;
      this.ruleForm.id = row.id;

      this.ruleForm.phones = row.user.phone;
      // this.ruleForm.usernames = row.user.username;
      // this.ruleForm.passwords = row.user.password;
      // this.ruleForm.roles_id = row.user.role[0].id;
      let arry = [];
      if (row.user.job_type) {
        row.user.job_type.forEach((item) => {
          arry.push(item.id);
        });
        this.ruleForm.job_type_arr = arry;
      } else {
        this.ruleForm.job_type_arr = [];
      }

      if (row.foreman_job_type) {
        let arrys = [];
        if (row.foreman_job_type.length > 0) {
          row.foreman_job_type.forEach((item) => {
            arrys.push(item.id);
          });
          this.ruleForm.foreman_job_type_ids = arrys;
        } else {
          this.ruleForm.foreman_job_type_ids = [];
        }
      }

      // this.ruleForm.job_type_ids=[] = row.job_type_id;
      this.ruleForm.address = row.address;
      this.ruleForm.native_place = row.native_place;
      this.ruleForm.emergency_contact = row.emergency_contact;
      this.ruleForm.emergency_contact_phone = row.emergency_contact_phone;
      this.ruleForm.card_number = row.card_number;
      this.ruleForm.base_pay = row.base_pay;
      this.ruleForm.hiredate = row.hiredate;
      this.ruleForm.level = row.level;
      this.ruleForm.is_foreman = row.is_foreman;
      this.title = "员工编辑";
      this.isProduct = true;
      this.isset = true;
      console.log(this.ruleForm);
    },
    handleSizeChange(val) {
      console.log(val);
      console.log(`每页 ${val} 条`);
    },
    handleCurrentChange(val) {
      console.log(`当前页: ${val}`);
      this.pagination.page = val;
      this.getlist();
    },
    prev() {
      this.pagination.page = this.pagination.page - 1;
      this.getlist();
    },
    next() {
      console.log("ss");
      this.pagination.page = this.pagination.page + 1;
      this.getlist();
    },
    changeValue() {
      this.$forceUpdate();
    },
  },
};
</script>

<style>
.s {
  display: flex;
  justify-content: space-around;
  align-items: center;
  text-align: right;
}
</style>
